package org.net.cms.uitl;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;

@Component
@Slf4j
public class JwtUtil {
    public static final long EXPIRE_TIME = 1000 * 60 * 60 * 4;
//    public static final Key APP_SECRET = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    public static final String APP_SECRET = "fC0qZ8k7K8m9n0p1q2r3s4t5u6v7w8x9y0z1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6";
//    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";


    public String getToken(String phone) {
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .claim("phone", phone)
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
    }

    public boolean checkToken(String token) {
        if (token == null || token.isEmpty()) {
            log.error("token为空");
            return false;
        }

        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
            return true;
        } catch (ExpiredJwtException e) {
           log.error("token已过期", e);
           return false;
        } catch (Exception e) {
            log.error("JWT未知错误", e);
            return false;
        }
    }

    public Claims getTokenBody(String token) {
        if (token == null || token.isEmpty()) {
            log.error("token为null");
            return null;
        }

        try {
            return Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }
}
